<template>
    <view>
        <!-- 预约临停 -->
        <topBar text="预约" :needBack="true"></topBar>
        <view style="position: relative;" :style="weixin !=2 ?'top:50rpx': ''">
            <!-- <view class="select">已选择</view> -->
			<view class="head-block" v-if="weixin == 2">
					     <view class="nav-title" :style="'top:10px'"></view>
						 <!-- 返回 -->
						 <view class="icon" @tap="goMy" :style="'top:6px'">
						      <van-icon name="arrow-left" color="#333" size="45rpx" />
						  </view>
				</view>
            <view class="card-top" >
                <image src="../../static/assets/img/card-lv-hover.png" class="bg-img" mode="widthFix"></image>
                <view class="card-order-l-t">
                    <view class="flex-rows">
                        <view class="row-title">车 位 号：</view>
                        <view class="row-text1-num">{{ spaceNo }}</view>
                    </view>
                    <view class="flex-rows" v-if="datas.realTime == '全部时间开放预约'">
                        <view class="row-title">全部时间开放预约</view>
                    </view>
                    <view v-else>
                        <view class="flex-rows">
                            <view class="row-title">共享日期：</view>
                            <view>
                                <view class="row-text1">{{ manage.validStartTime1 }}~{{ manage.validEndTime1 }} {{ manage.addCycleName }}</view>
                            </view>
                        </view>
                        <view class="flex-rows">
                            <view class="row-title">价 格：</view>
                            <view class="row-text1">{{ manage.unitPrice / 100 }}元/次</view>
                        </view>
						<view class="row-text2" style="margin-bottom: 10rpx;" v-if="manage.haveCharge ? manage.haveCharge : datas.haveCharge">
						    <view>（本车位可提供充电服务，费用双方自行商议）</view>
						    <!-- <view>（国标/特斯拉专用）</view> -->
						</view>
                    </view>
                    <view class="flex-rows">
                        <view class="row-title">共享时段：</view>
                        <view class="row-text1">{{ manage.validStartTime2 }}-{{ manage.validEndTime2 }}</view>
                    </view>
                    <view class="statu" style="display: flex; margin: 15rpx 0; min-height: 34rpx">
                        <view class="statuView" v-if="manage.haveCharge ? manage.haveCharge : datas.haveCharge">
                            <image class="img-tag" mode="widthFix" src="../../static/assets/img/elc.png" />
                            有充电桩
                        </view>
                        <view class="statuView" v-if="manage.buildType ? manage.buildType : datas.buildType == 2">
                            <image class="img-tag" mode="widthFix" src="../../static/assets/img/under.png" />
                            地下
                        </view>
                        <view class="statuView" v-if="manage.buildType ? manage.buildType : datas.buildType == 1">
                            <image class="img-tag" mode="widthFix" src="../../static/assets/img/ground.png" />
                            地面
                        </view>
                        <view class="statuView" v-if="manage.buildType ? manage.buildType : datas.buildType == 3">
                            <image class="img-tag" mode="widthFix" src="../../static/assets/img/3dpark.png" />
                            立体车库
                        </view>
                    </view>
                    <van-rate readonly :size="15" v-model="evaluate" color="#ffd21e" void-icon="star" void-color="#eee" />
                </view>
                <view>
                    <view
                        :class="'parkrecommend ' + (focus == 1 ? 'like1' : 'nolike1') + ' '"
                        :data-item="datas"
                        :data-index="index"
                        :data-isFocus="focus"
                        :data-id="(spaceNo ? spaceNoId : datas.parkingCode)"
                        @tap.stop.prevent="likeThisPark"
                    >
                        {{ focus == 1 ? '已关注' : '+关注' }}
                    </view>
                    <view
                        class="concant"
                        :data-item="manage"
                        :data-index="index"
                        :data-id="(spaceNo ? spaceNoId : datas.parkingCode)"
                        @tap="gotoMessage"
                        :data-url="'../socks/socks?manageId=' + manage.id + '&recipientUserId=' + manage.identityId + '&otherName=' + manage.manageName"
                    >
                        <image src="../../static/assets/img/message.png" class="img-msg"></image>
                        留言咨询
                    </view>
                </view>
            </view>
            <view class="split-line"></view>
            <!-- 选择日期start -->
            <view class="card-middle">
                <!-- <view class="park-title">请选择：</view> -->
                <view class="cell-btm">
                   <van-cell title="预约日期"  is-link @click="showParkFun">
                        <span :class="parkTimeStart != '请选择' ? 'infoText' : ''">{{ parkTimeStart }}</span>
                    </van-cell>
<!--                    <van-cell title="预计离场时间" is-link  @click="showPark2Fun">
						<span :class="parkTimeEnd != '请选择' ? 'infoText' :''">{{parkTimeEnd}}</span>
					</van-cell> -->
                    <van-cell title="您的车牌号" is-link @click="showCarFun">
                        <span :class="carNo != '请选择' ? 'infoText' : ''">{{ carNo }}</span>
                    </van-cell>
                </view>
            </view>
            <!-- 选择日期end -->
            <view class="tips-box">
                <view class="tip-title">
                    <image src="../../static/assets/img/usetip.png"></image>
                    使用须知：
                </view>
                <view class="tip-content">1、购买次数后，可在预约日期当天共享时段内无限次出入。</view>
                <view class="tip-content">2、请在车位共享时段内使用，超时停车行为将列入黑名单影响后续正常使用。</view>
                <view class="tip-content">3、预约当日订单不可取消。</view>
            </view>

            <view class="btn" @tap="submit(datas.lltParkingInfoType)">预约车位</view>
            <view class="rule">
                <van-checkbox v-model="checked" checked-color="#00BCAB"></van-checkbox>
                <text @tap="showRule" class="rule-konw">
                    我已经阅读并同意
                    <text style="color: #00bcab">《停车服务协议》</text>
                </text>
            </view>
        </view>
        <view>
            <van-popup round v-model="showRulePop" @close="closeRule">
                <view class="rules">
                    <view class="rule-title">停车服务协议</view>
                    <!-- <view class="rule-content">{{platformRules}}</view> -->
                    <view class="rule-content">
                        <rich-text :nodes="platformRules"></rich-text>
                    </view>
                    <view class="rule-line"></view>
                    <view class="rule-know" @tap="closeRule">我知道了</view>
                </view>
            </van-popup>
        </view>
        <!-- 车辆下拉 -->
        <van-popup v-model="showCar" position="bottom" @close="onCloseCar">
            <van-picker show-toolbar :columns="carList" @confirm="onSelectCar" @cancel="onCloseCar" />
        </van-popup>
        <!-- 时间下拉 -->
        <van-popup v-model="showPark" position="bottom" @close="oncloseParkTime">
            <van-datetime-picker
                type="date"
                title="选择到达时间"
                v-model="currentDate"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="SelectDate"
                @cancel="oncloseParkTime"
                :formatter="formatter"
            />
        </van-popup>
        <!-- 时间下拉 -->
        <van-popup v-model="showPark2" position="bottom" @close="oncloseParkTime2">
            <van-datetime-picker
                type="datetime"
                title="选择离场时间"
                v-model="currentDate2"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="SelectDate2"
                @cancel="oncloseParkTime2"
                :formatter="formatter"
            />
        </van-popup>
        <van-dialog id="van-dialog" />
        <van-toast id="van-toast" />
        <van-dialog
            id="van-dialog2"
            v-model="isShowPayTip"
            title="支付提醒"
            confirm-button-text="去支付"
            cancel-button-text="稍后再看"
            confirm-button-color="#00BCAB"
            cancel-button-color="#AEAEAE"
            v-model-cancel-button="true"
            message="您有订单未支付，请尽快支付"
            @confirm="gotoPay($event, { tagId: 'van-dialog2' })"
        />
    </view>
</template>

<script>
// import vanCell from '@vant/weapp/cell/index';
// import vanCellGroup from '@vant/weapp/cell-group/index';
// import vanCheckbox from '@vant/weapp/checkbox/index';
// import vanDatetimePicker from '@vant/weapp/datetime-picker/index';
// import vanPicker from '@vant/weapp/picker/index';
import config from './../../utils/config.js';
import util from './../../utils/util.js';
import api from './../../utils/api.js';
import { Dialog } from 'vant';
// import Toast from '@vant/weapp/toast/toast';
export default {
    components: {
        // vanCell,
        // vanCellGroup,
        // vanCheckbox,
        // vanDatetimePicker,
        // vanPicker
    },
    data() {
        return {
            focus: 0,
            carNo: '请选择',
            parkTimeStart: '请选择',
            parkTimeEnd: '',
            showCar: false,
            showPark: false,
            showPark2: false,
			show2:false,
            checked: false,
            showRulePop: false,
			currentTime:'',
            datas: {
                haveCharge: '',
                buildType: 0,
                parkingCode: ''
            },

            rules1: '',
			index:'',
            carList: '',
            minDate: new Date(),
            maxDate: new Date(new Date(new Date().toLocaleDateString()).getTime() +24 * 60 * 60 * 1000 -1),
            minDate2: new Date().getTime(),
            maxDate2: new Date(new Date().getTime() + 24 * 60 * 60 * 1000).getTime(),
            st1: '',
            st2: '',
            ed1: '',
            ed2: '',
            currentDate: new Date().getTime() + 60 * 15 * 1000,

            //当前时间+15分钟
            currentDate2: new Date().getTime(),

            filter(type, options) {
                if (type === 'minute') {
                    return options.filter((option) => option % 15 === 0);
                }

                return options;
            },

            platformRules: config.platformRules,

            formatter(type, value) {
                if (type === 'year') {
                    return `${value}年`;
                }

                if (type === 'month') {
                    return `${value}月`;
                }

                if (type === 'day') {
                    return `${value}日`;
                }

                if (type === 'hour') {
                    return `${value}时`;
                }

                if (type === 'minute') {
                    return `${value}分`;
                }

                return value;
            },

            isShowPayTip: false,
            gotopayType: '',
            price: {},

            //车位号
            spaceNo: '',

            spaceNoId: '',
            type: '',
            evaluate: '',
			weixin:uni.getStorageSync('weixin'),
            manage: {
                validStartTime1: '',
                validEndTime1: '',
                addCycleName: '',
                unitPrice: 0,
                haveCharge: false,
                validStartTime2: '',
                validEndTime2: '',
                buildType: false,
                id: '',
                identityId: '',
                manageName: ''
            },
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.focus) {
            this.setData({
                focus: options.focus
            });
        }

        if (options.spaceNoId) {
            this.setData({
                spaceNoId: options.spaceNoId
            });
        }

        if (options.spaceNo) {
            this.setData({
                spaceNo: options.spaceNo
            });
        }

        if (options.type) {
            this.setData({
                type: options.type
            });
        }

        let param = {
            parkingCode: options.param,
            type: 1,
            spaceNo: this.spaceNo ? this.spaceNo : ''
        };
        util.request(api.findProductList, param, 'GET').then((res) => {
            if (res.success) {
                let list = res.data.productList;

                if (list) {
                    list.map((item) => {
                        if (item.type == 3) {
                            this.setData({
                                price: item
                            });
                        }
                    });
                }

                if (res.data && res.data.manage) {
                    res.data.manage.validStartTime1 = res.data.manage.validStartTime.split(' ')[0];
                    res.data.manage.validEndTime1 = res.data.manage.validEndTime.split(' ')[0];
                    res.data.manage.validStartTime2 = res.data.manage.tempStartTime || res.data.manage.validStartTime.split(' ')[1];
                    res.data.manage.validEndTime2 = res.data.manage.tempEndTime || res.data.manage.validEndTime.split(' ')[1];
                    res.data.manage.tempCycle2 = res.data.manage.tempCycle.split('');

                    if (res.data.manage != null) {
                        //包月的显示 全天（默认）
                        if (res.data.manage.tempCycle == '0000000' || res.data.manage.tempCycle == null) {
                            res.data.manage.addCycleName = '不重复';
                        } else if (res.data.manage.tempCycle == '1111111') {
                            res.data.manage.addCycleName = '每天';
                        } else {
                            let cy = res.data.manage.tempCycle.split('');
                            res.data.manage.addCycleName = '每周';

                            if (cy[0] == 1) {
                                res.data.manage.addCycleName += '一 ';
                            } else {
                                res.data.manage.addCycleName += '';
                            }

                            if (cy[1] == 1) {
                                res.data.manage.addCycleName += '二 ';
                            } else {
                                res.data.manage.addCycleName += '';
                            }

                            if (cy[2] == 1) {
                                res.data.manage.addCycleName += '三 ';
                            } else {
                                res.data.manage.addCycleName += '';
                            }

                            if (cy[3] == 1) {
                                res.data.manage.addCycleName += '四 ';
                            } else {
                                res.data.manage.addCycleName += '';
                            }

                            if (cy[4] == 1) {
                                res.data.manage.addCycleName += '五 ';
                            } else {
                                res.data.manage.addCycleName += '';
                            }

                            if (cy[5] == 1) {
                                res.data.manage.addCycleName += '六 ';
                            } else {
                                res.data.manage.addCycleName += '';
                            }

                            if (cy[6] == 1) {
                                res.data.manage.addCycleName += '日';
                            } else {
                                res.data.manage.addCycleName += '';
                            }
                        }

                        res.data.manage.validStartTime = res.data.manage.validStartTime.toString().split(' ')[0] || '';
                        res.data.manage.validEndTime = res.data.manage.validEndTime.toString().split(' ')[0] || '';
                    }
                }

                this.setData({
                    datas: res.data.parkingInfo,
                    evaluate: res.data.evaluate,
                    manage: res.data.manage ? res.data.manage : {},
                });
            }
        });
        this.setData({
            // rules1:param.rules1,
            carList: uni.getStorageSync('plateNos').split(','),
            carNo: uni.getStorageSync('plateNos').split(',')[0] || '请选择'
        });
        var date = new Date(); //1. js获取当前时间

        var min = date.getMinutes(); //2. 获取当前分钟

        date.setMinutes(min + 1);
        this.setData({
            // minDate: new Date().getTime(),
            // maxDate: new Date().getTime(),
            //new Date().getTime() + 60 * 60 * 24 * 1000
            currentDate: new Date().getTime() + 60 * 15 * 1000
        });
        this.setData({
            // currentDate2: this.currentDate + 60 * 1000,
            // minDate2: this.currentDate + 60 * 1000,
            maxDate2: new Date(new Date().toLocaleDateString()).getTime() + 2 * 24 * 60 * 60 * 1000 - 1 //this.data.currentDate + 60 * 60 * 24 * 1000
        });
        this.setData({
            parkTimeStart: util.getDate(this.currentDate, 'yyyy-MM-dd') // parkTimeEnd:util.getDate(this.data.currentDate2,'yyyy-MM-dd')
        }); // 从车位列表页进来的---访客身份下--暂时废弃
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    // onShareAppMessage: function () {
    // }
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */ methods: {
		 goMy() {
		 		     uni.navigateBack({
		 		         delta: 1
		 		     });
		 		 },
        //留言咨询
        gotoMessage(e) {
            const identityId = uni.getStorageSync('identityId');
            let recipientUserId = e.currentTarget.dataset.item.identityId;

            if (identityId == recipientUserId) {
                uni.showToast({
                    title: '抱歉，这个车位为你自己的车位！',
                    icon: 'none'
                });
                return;
            }

            let url = e.currentTarget.dataset.url;
            uni.navigateTo({
                url
            });
        },

        likeThisPark(event) {
            //关注车场
            let that = this;
            if (event.currentTarget.dataset.id) {
                if (that.spaceNo) {
                    //关注车位
                    let type = event.currentTarget.dataset.isfocus == 1 ? 2 : 1; //1关注，2取消关注

                    util.request(api.manageAddOrUpdateFocus + '?unionId=' + uni.getStorageSync('unionId') + '&manageId=' + event.currentTarget.dataset.id + '&type=' + type, 'get')
                        .then((res) => {
                            if (res.success) {
                                if (event.currentTarget.dataset.isfocus == 1) {
                                    //取消关注成功
                                    this.setData({
                                        focus: 0
                                    });
                                    uni.showToast({
                                        title: '取消关注成功'
                                    });
                                } else if (event.currentTarget.dataset.isfocus == 0) {
                                    //添加关注成功
                                    this.setData({
                                        focus: 1
                                    });
                                    uni.showToast({
                                        title: '关注成功'
                                    });
                                    uni.requestSubscribeMessage({
                                        tmplIds: ['G-qqlo3c5ARPqg9lPCnCrSUxAEgZ8bPfrEpd0UVE-8o'],

                                        success(sus) {},

                                        fail(err) {}
                                    });
                                }

                                if (this.active == 0) {
                                    this.getTempList();
                                } else if (this.active == 1) {
                                    this.getMonthList();
                                }
                            } else {
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'none'
                                });
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                } else {
                    //关注车场
                    let type = this.focus == 1 ? 2 : 1; //1关注，2取消关注

                    util.request(api.addOrUpdateFocus + '?unionId=' + uni.getStorageSync('unionId') + '&parkingCode=' + this.datas.parkingCode + '&type=' + type, 'get')
                        .then((res) => {
                            if (res.success) {
                                if (event.currentTarget.dataset.isfocus == 1) {
                                    //取消关注成功
                                    this.setData({
                                        focus: 0
                                    });
                                    uni.showToast({
                                        title: '取消关注成功'
                                    });
                                } else if (event.currentTarget.dataset.isfocus == 0) {
                                    //添加关注成功
                                    this.setData({
                                        focus: 1
                                    });
                                    uni.showToast({
                                        title: '关注成功'
                                    });
                                    uni.requestSubscribeMessage({
                                        tmplIds: ['G-qqlo3c5ARPqg9lPCnCrSUxAEgZ8bPfrEpd0UVE-8o'],

                                        success(sus) {},

                                        fail(err) {}
                                    });
                                }
                            } else {
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'none'
                                });
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                }
            }
        },

        onChange(event) {
            this.setData({
                checked: event.detail
            });
        },

        submit(lltParkingInfoType) {
            if (this.carNo == '请选择') {
				uni.showToast({
				    title: '请选择车辆',
				    icon: 'none'
				});
                return;
            }

            if (this.parkTimeStart == '请选择') {
				uni.showToast({
				    title: '请选择到达时间',
				    icon: 'none'
				});
                return;
            }
			 // if (this.parkTimeEnd == '请选择') {
    //           Toast('请选择离场时间')
    //           return
    //         }

            if (this.checked == false) {
				uni.showToast({
				    title: '请勾选同意《停车服务协议》',
				    icon: 'none'
				});
                return;
            }
			var myDate = new Date();
            let param = {
                unionId: uni.getStorageSync('unionId'),
                startTime:util.getDate(myDate, 'yyyy-MM-dd hh:mm:ss'),
				endTime:util.getDate(myDate, 'yyyy-MM-dd') + ' 23:23:00',
                parkingCode: this.datas.parkingCode,
                plateNo: this.carNo,
                rentedType: '1',
				manageId:this.manage.id	
            };

            if (uni.getStorageSync('visitor_code')) {
                param.visitInviteCode = uni.getStorageSync('visitor_code');
            }

            if (this.spaceNo != '') {
                param.spaceNo = this.spaceNo;
            }

            uni.showLoading({
                title: '加载中'
            });
            let that = this;
			var payType = uni.getStorageSync('weixin') == 2 ? 2 : 1
			param.payType = payType
			if(payType == 2){
				util.request(api.unionPayTmpParkingBook, param, 'POST')
				    .then((res) => {
				        uni.hideLoading();
				        if (res.success) {
							if(lltParkingInfoType == 3){
								var {url,content,wxContent} = JSON.parse(res.data)
								jWeixin.miniProgram.navigateTo({url:"/pages/wxContent/wxContent?param=" + wxContent})
							}else{
								let param = encodeURIComponent(res.data);
								uni.showToast({
								    title: '提交成功'
								});
								uni.navigateTo({
								    url: '../wechatPay/wechatPay?param=' + param + "&from=01"
								});

							}
								uni.removeStorageSync('visitor_code');
								uni.removeStorageSync('visitor_parkcode');
				        } else if (res.busiCode == 'waitingToPay1') {
				            this.setData({
				                gotopayType: 1,
				                isShowPayTip: true
				            });
				        } else if (res.busiCode == 'waitingToPay2') {
				            this.setData({
				                gotopayType: 2,
				                isShowPayTip: true
				            });
				        } else {
				            Dialog.alert({
				                message: res.msg || '预约失败，请重试',
				                confirmButtonText: '确定'
				            }).then(() => {
				                // on close
				            });
				        }
				    })
				    .catch((err) => {
				        Toast(err || '接口出错了，请重试');
				    });
			}else{
				util.request(api.parkSpaceBook, param, 'post').then((res) => {
				    if (res.code == 0) {
				        const data = res.data;
						if(lltParkingInfoType == 3){
							var {url,content} = JSON.parse(data)
							console.log(url,content)
							window.location.href = url + '?' + content
						}else{
							document.querySelector('body').innerHTML = res.data;
							document.forms[0].submit()
						}
				    } else {
				        uni.showToast({
				            title: res.msg,
				            icon: 'none'
				        });
				    }
				});
			}
            
        },

        /**
         * 选择停车时间
         */
        SelectDate(e) {
            console.log(e);
            this.setData({
                showPark: false,
                parkTimeStart: util.getDate(e, 'yyyy-MM-dd'),
                // parkTimeEnd:util.getDate(e.detail+60*1000,'yyyy-MM-dd hh:mm'),
                minDate2: e.detail + 60 * 1000,
                maxDate2: e.detail + 60 * 60 * 24 * 1000
            });
        },

        SelectDate2(e) {
            this.setData({
                showPark2: false,
                parkTimeEnd: util.getDate(e, 'yyyy-MM-dd hh:mm')
            });
        },

        /**
         * 选择停车车辆
         */
        onSelectCar(e) {
            console.log(e);
            this.setData({
                carNo: e,
                showCar: false
            });
        },

        showCarFun() {
            this.setData({
                showCar: true
            });
        },

        showParkFun() {
            this.setData({
                showPark: true
            });
        },

        showPark2Fun() {
            this.setData({
                showPark2: true
            });
        },

        showRule() {
            this.setData({
                showRulePop: true
            });
        },

        closeRule() {
            this.setData({
                showRulePop: false,
                checked: true
            });
        },

        onCloseCar() {
            this.setData({
                showCar: false
            });
        },

        oncloseParkTime() {
            this.setData({
                showPark: false
            });
        },

        oncloseParkTime2() {
            this.setData({
                showPark2: false
            });
        },

        /**跳转支付 */
        gotoPay(e, _dataset) {
            /* ---处理dataset begin--- */
            this.datasetHandle(e, _dataset);
            /* ---处理dataset end--- */
            uni.navigateTo({
                url: '../order/index?type=' + this.gotopayType
            });
        }
    }
};
</script>
<style>
@import './newBookparkPerson.css';
</style>
